package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service("mailService")
public class MailService {

    //发送邮件类
    @Autowired
    private JavaMailSender javaMailSender;


    //发送发邮箱信息 //@Value读取配置信息
    @Value("${spring.mail.username}")
    private String fromMail;


    public void sendMail(String toMail,String context) {
        System.out.println("发送邮件测试1");
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
        try {
            mimeMessageHelper.setFrom(fromMail); //发送方邮箱
            mimeMessageHelper.setTo(toMail); //接收方邮箱
            mimeMessageHelper.setText(context,false);//发送文本内容
            mimeMessageHelper.setSubject("测试邮件"); //发送主题


            javaMailSender.send(mimeMessage);
            System.out.println("发送成功");
        } catch ( MessagingException e) {
            System.out.println("发送失败");
            e.printStackTrace();
        }
    }
}
